﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.FriendlyException;
using HOPU.OnlineSchool.Application.Courses.Dtos;
using HOPU.OnlineSchool.Core;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace HOPU.OnlineSchool.Application.Courses.Services
{
    public class CourseService : ICourseService, ITransient
    {
        private readonly IRepository<EduCourse> _courseRepository;
        private readonly IRepository<EduSubject> _subjectRepository;
        private readonly IRepository<EduTeacher> _teacherRepository;

        public CourseService(IRepository<EduCourse> courseRepository, IRepository<EduSubject> subjectRepository, IRepository<EduTeacher> teacherRepository)
        {
            this._courseRepository = courseRepository;
            this._subjectRepository = subjectRepository;
            _teacherRepository = teacherRepository;
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedList<EduCourse>> GetListSync(int page, int limit, CouseSearchDto input)
        {
            var query =  _courseRepository.Where(m => m.IsDeleted == 0);
            if (!string.IsNullOrEmpty(input.SubjectId))
            {
                query = query.Where(m => m.SubjectId == input.SubjectId);
            }
            if (!string.IsNullOrEmpty(input.SubjectParentId))
            {
                query = query.Where(m => m.SubjectParentId == input.SubjectParentId);
            }
            if (!string.IsNullOrEmpty(input.Title))
            {
                query = query.Where(m => m.Title.Contains(input.Title));
            }
            if (!string.IsNullOrEmpty(input.TeacherId))
            {
                query = query.Where(m => m.TeacherId == input.TeacherId);
            }

            //分页
            var list = await query.OrderByDescending(m => m.GmtCreate).ToPagedListAsync(page, limit);
            return list;
        }
        /// <summary>
        /// 添加课程
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns> Task<string> AddSync(TeacherAddDto teacher);
        public async Task<string> AddSync(EduCourse model)
        {
            //var model = input.Adapt<EduTeacher>();//将添加数据模型转换为数据库数据模型

            //通过雪花算法生成主键id
            model.Id = YitIdHelper.NextId().ToString();
            model.Status = "Draft";
            model.GmtCreate = DateTime.Now;
            model.GmtModified = DateTime.Now;
            await _courseRepository.InsertAsync(model);
            return "添加成功";
        }

        //获取课程目录的 下拉框数据
        public async Task<List<SelectDto>> GetSubjectSelect(string parentId)
        {
            var list = await _subjectRepository.Entities.AsNoTracking().ToListAsync();
            var selectList = new List<SelectDto>();
            if (string.IsNullOrEmpty(parentId))
            {
                selectList = list.Where(e => e.ParentId == "0").Select(e => new SelectDto() { Value = e.Id, Label = e.Title }).ToList();
            }
            else
            {
                selectList = list.Where(e => e.ParentId == parentId).Select(e => new SelectDto() { Value = e.Id, Label = e.Title }).ToList();

            }

            return selectList;
        }

        //获取教师的 下拉框数据
        public async Task<List<SelectDto>> GetTeacherSelect()
        {
            var list = await _teacherRepository.Entities.AsNoTracking().ToListAsync();
            var selectList = new List<SelectDto>();
            
          selectList = list.Select(e => new SelectDto() { Value = e.Id, Label = e.Name }).ToList();
           

            return selectList;
        }
        /// <summary>
        /// 删除课程
        /// </summary>
        /// <param name="id"></param>
        public async Task<string> DeleteSync(string id)
        {
            var model = await _courseRepository.FirstOrDefaultAsync(e => e.IsDeleted == 0 && e.Id == id);
            if (model == null)
                throw Oops.Oh("该课程已经被删除");
            model.IsDeleted = 1;
            model.GmtModified = DateTime.Now;

            //更新指定的字段信息
            await _courseRepository.UpdateIncludeAsync(model, new string[] { nameof(model.IsDeleted), nameof(model.GmtModified) });
            return "删除成功";
        }
        // <summary>
        /// 根据id获取课程
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<EduCourse> GetCourseAsync(string id)
        {
            var model = await _courseRepository.FirstOrDefaultAsync(t => t.Id == id && t.IsDeleted == 0);
            if (model == null)
                throw Oops.Oh("该讲师未找到");
            return model;
        }
        /// <summary>
        /// 更新课程
        /// </summary>
        /// <param name="id"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task UpdateAsync(string id, EduCourse teacher)
        {
            var exists = await _courseRepository.AnyAsync(t => t.Id == id && t.IsDeleted == 0);
            if (!exists)
                throw Oops.Oh("该讲师未找到");
            await teacher.UpdateExcludeAsync(new[] { nameof(teacher.GmtCreate), nameof(teacher.IsDeleted) });
        }
    }
}
